package org.komarichin.struts2.actions.customer;

import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.komarichin.jpa.entity.IUser;
import org.komarichin.jpa.entity.IRole;
import org.komarichin.jpa.service.IUserService;
import org.komarichin.jpa.service.exceptions.DublicateUserException;
import org.komarichin.struts2.BaseAction;
import org.komarichin.struts2.beans.Customer;
import org.komarichin.struts2.beans.ICustomer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * User: Michael Komarichin
 * Date: 29.09.2009
 * Time: 9:59:59
 */
public class CustomerAction extends BaseAction {
    private static final Logger log = LoggerFactory.getLogger(CustomerAction.class);

    @Autowired
    protected IUserService userService;

    private String login;
    private String password;
    private String confirmPassword;
    private String hint;

    public String login() throws Exception {
        log.debug("logining user...");
        IUser user = null;
        if (!isLogged()) {
            user = userService.login(login, password);
            if (user != null) {
                Map<String, Object> session = ActionContext.getContext().getSession();
                IRole role = userService.getRoleById(user.getRole());
                session.put(CUSTOMER_KEY, new Customer(user, role));
                log.info("user {} logged successfull", user.getLogin());
                addActionMessage("user logged");
            } else {
                log.warn("incorrect user login or password");
                addActionError("incorrect user login or password");
                return INPUT;
            }
        } else {
            log.warn("user logged");
            addActionError("user logged");
            return INPUT;
        }

        return SUCCESS;
    }

    public String logout() throws Exception {
        Map<String, Object> session = ActionContext.getContext().getSession();
        if (session != null && session.get(CUSTOMER_KEY) != null && session.get(CUSTOMER_KEY) instanceof ICustomer) {
            ICustomer user = (ICustomer) session.get(CUSTOMER_KEY);
            log.debug("start invalidate user {} session...", user.getUser());
            ServletActionContext.getRequest().getSession(false).invalidate();
            log.info("User {} worked done. User session invalidated", user.getLogin());
        }
        return SUCCESS;
    }


    public String enroll() throws Exception {
        //todo add validation in xml
        IUser user = userService.enroll(login, password, hint);
        addActionMessage("enroll user success");
        return SUCCESS;
    }

    public List<IUser> getUsers() {
        log.debug("getUsers");
        Map<String, Object> session = ActionContext.getContext().getSession();
        List<IUser> result = null;
        if (session != null && session.get(CUSTOMER_KEY) != null && session.get(CUSTOMER_KEY) instanceof ICustomer) {
            ICustomer user = (ICustomer) session.get(CUSTOMER_KEY);

            result = userService.getAllowUsers(user.getRole().getPermission());
        }
        log.debug("result: {}", result);
        return result;
    }

    public String initSystem() {
        log.info("start inititialize system...");
        IRole role = userService.createSystemRole();
        IUser user = userService.findByName("root");
        if (user == null) {
            try {
                user = userService.enroll("root", "root", "root");
            } catch (DublicateUserException e) {
                log.error(e.getMessage(), e);
            }
        }
        user.setRole(role.getId());
        userService.updateUser(user);

        log.info("end initialize system.");
        return SUCCESS;
    }

    /**
     * forgot user password when user login and hint exists in db
     *
     * @return forward name
     */
    public String forgot() {
        return SUCCESS;
    }

    /**
     * ajax cheching existing login
     *
     * @return forward name
     */
    public String loginValidate() {
        if (StringUtils.isNotEmpty(login)) {
            if (userService.isUserExists(login)) {
                addActionError("errror1");
            } else addActionMessage("messs1");
        } else {
            addActionError("error2");
        }
        return SUCCESS;
    }

    /**
     * ajax cheching password and confirm password
     *
     * @return forward name
     */
    public String passwordValidate() {
        if (StringUtils.isNotEmpty(password) &&
                StringUtils.isNotEmpty(confirmPassword)) {
            if (password.equals(confirmPassword))
                addActionMessage("success mess");
            else
                addActionError("password not equals confirm password");
        } else {
            addActionError("password can't be null");
        }
        return SUCCESS;
    }


    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getConfirmPassword() {
        return confirmPassword;
    }

    public void setConfirmPassword(String confirmPassword) {
        this.confirmPassword = confirmPassword;
    }

    public String getHint() {
        return hint;
    }

    public void setHint(String hint) {
        this.hint = hint;
    }


}
